import { useModal } from '@/hooks';
import { Modal } from '@/components';
import { useState } from 'react';
import { useMutation } from 'react-query';
import { request } from '@/request';

const Username = ({ value, onSubmit }) => {
   const { isOpen, openModal, closeModal } = useModal();
   const [name, setNamee] = useState(value);
   const handleChange = (e) => {
      const value = e.target.value;
      setNamee(value);
   };

   const { mutate } = useMutation({
      mutationFn: () =>
         request('/user/username', {
            method: 'POST',
            data: {
               username: name,
            },
            showSuccess: true,
            success: () => {
               onSubmit();
               closeModal();
            },
         }),
   });

   const handleSubmit = () => {
      mutate();
   };

   return (
      <div>
         <Modal
            isOpen={isOpen}
            header="修改用户名"
            footer={[
               <div
                  className="color-disabled"
                  onClick={closeModal}
                  key="cancel"
               >
                  取消
               </div>,
               <div className="color-main" onClick={handleSubmit} key="sure">
                  确定
               </div>,
            ]}
         >
            <input value={name} onChange={handleChange} className="w-full" />
         </Modal>
         <div onClick={openModal}>{value}</div>
      </div>
   );
};

export default Username;
